using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;


public class Main : MonoBehaviour
{
    public GameQuit gameQuitScrpts;
    public static Main Instance;
    public void Awake()
    {
        Instance = this;
      
    }

    public int StartNum =0;

    public int[,] array = new int[4, 4];
    private Text[,] textarray = new Text[4, 4];

    // public bool isMoveToRandom2 = false;
    private void Start()
    {
        
        this.gameObject.AddComponent<UIMgr>();
        this.gameObject.AddComponent<AutioMgr>();
        this.gameObject.AddComponent<GameQuit>();

    }

    //
    // private bool _A_isEnd = false;
    // private bool _W_isEnd = false;
    // private bool _S_isEnd = false;
    // private bool _D_isEnd = false;
    private void Update()
    {
        if (StartNum==0)
            return;
        if (_end_game())
        {
        if (Input.GetKeyDown(KeyCode.D))
        {
            _X_Right(array);
            _randomTo2();
            _count = 0;
            _init_textArray();
            onClickAudio();

        }else if (Input.GetKeyDown(KeyCode.A))
        {
            _X_left(array);
            _randomTo2();
            _count = 0;
            _init_textArray();
            onClickAudio();
        }else if(Input.GetKeyDown(KeyCode.W))
        {
            _Y_Up(array);
            _randomTo2();
            _count = 0;
            _init_textArray();
            onClickAudio();
        }
        else if(Input.GetKeyDown(KeyCode.S))
        {
            _Y_Down(array);
            _randomTo2();
            _count = 0;
            _init_textArray();
            onClickAudio();
        }
        
        // else if (Input.GetKeyDown(KeyCode.Space))
        // {
        //     if (isHaveKong())
        //         _randomTo2();
        //     _init_textArray();
        //     onClickAudio();
        // }
        else if (Input.GetKeyDown(KeyCode.Escape))
        {
            StartNum = 0;
            UIMgr.Instance.show_ESC(true);
            onClickAudio();
            

        }
        }
    }

    public void onClickAudio()
    {
        AutioMgr.Instance.OnclickAudio();
    }

    public bool _end_game()
    {

        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                if (array[i, j] != 0)
                {
                    if (array[i, j] == 2048)
                    {
                        UIMgr.Instance.show_ESC(true);
                        UIMgr.Instance._start_panel.transform.GetChild(0).GetComponent<Text>().text = "游戏胜利";
                        return false;
                    }

                    if (isEnd)
                    {
                        #region 之前
                        /*
                        if (Input.GetKeyDown(KeyCode.D))
                        {
                            _D_isEnd = !isHaveKong();
                            Debug.Log("_D_isEnd"+_D_isEnd);
                        }else if (Input.GetKeyDown(KeyCode.A))
                        {
                            _A_isEnd = !isHaveKong();
                            Debug.Log("_A_isEnd"+_A_isEnd);

                        }else if(Input.GetKeyDown(KeyCode.W))
                        {
                            _W_isEnd = !isHaveKong();
                            Debug.Log("_W_isEnd"+_W_isEnd);

                        }
                        else if(Input.GetKeyDown(KeyCode.S))
                        {
                            _S_isEnd = !isHaveKong();
                            Debug.Log("_S_isEnd"+_S_isEnd);

                        }

                        // if (!isHaveKong()&&(_D_isEnd||_A_isEnd||_W_isEnd||_S_isEnd))
                        // {
                        //     _D_isEnd = false;
                        //     _A_isEnd = false;
                        //     _W_isEnd = false;
                        //     _S_isEnd = false;
                        //
                        // }
                        Debug.Log($"_D_isEnd:{_D_isEnd} _A_isEnd {_A_isEnd} _W_isEnd{_W_isEnd}_S_isEnd{_S_isEnd}");
                        if (_D_isEnd&&_S_isEnd&&_W_isEnd&&_A_isEnd)
                        {
                            UIMgr.Instance.show_ESC(true);
                            UIMgr.Instance._start_panel.transform.GetChild(0).GetComponent<Text>().text = "游戏失败";
                            isEnd=_D_isEnd = _A_isEnd = _S_isEnd = _W_isEnd = false;
                            return false;
                        }
                        */
                        #endregion

                        if (gameQuitScrpts.Check_Up_Down_Left_Right())
                        {
                            UIMgr.Instance.show_ESC(true);
                            UIMgr.Instance._start_panel.transform.GetChild(0).GetComponent<Text>().text = "游戏失败";
                            isEnd = false;
                            return false;
                        }
                        isEnd = false;

                    }
                }
            }
        }
        return true;
    }


    private Dictionary<int, int[]> dic = new Dictionary<int, int[]>();
    // private List<Dictionary<int, int>> list = new List<Dictionary<int, int>>();

    private int _count = 0;
    public void _randomTo2()
    {
        
        // if(!isMoveToRandom2)
        //     return;
        int index=0;
        int[] arrayIndex =null; 
        for (int k = 0; k < array.GetLength(0); k++)
        {
         
            for (int l = 0; l < array.GetLength(1); l++)
            {
                if (array[k, l] == 0)
                {
                    arrayIndex = new int[2];
                    arrayIndex[0] = k;
                    arrayIndex[1] = l;
                    dic.Add(index,arrayIndex);
                    index++;
                }
            }
            // list.Add(dic);
        }

        if (index==0)
            return;

        
        int[] num = {2, 4, 8};
        int n =Random.Range(0, 3);
        index = Random.Range(0, dic.Count);
        arrayIndex = dic[index];
        dic.Clear();
        if (_count>0)
            return;
        array[arrayIndex[0],arrayIndex[1]] = num[n];
        _count = 1;
        // isMoveToRandom2 = false;
    }   
    
    


    /// <summary>
    /// 生成二维数组
    /// </summary>
    public void _init_birthArray()
    {
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                array[i, j] = 0;
                textarray[i, j] = GameObject.Find("array" + i).transform.GetChild(j).gameObject.GetComponent<Text>();
            }
        }
        Start_randomNum2();
        _init_textArray();
    }
    
    /// <summary>
    /// 实时更新text
    /// </summary>
    public void _init_textArray()
    {
        if(!textarray[0,0].gameObject.transform.parent.gameObject.activeSelf)
            return;
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                if (array[i,j] ==0)
                {
                    textarray[i,j].text = " ";
                }
                else
                {
                    textarray[i, j].text = array[i, j].ToString();
                }
                
            }
        }

    }
    /// <summary>
    /// 开局生成随机4位数
    /// </summary>
    public void Start_randomNum2()
    {
        int i, j, n;
        int[] num = {2, 4, 8};
        for (int k = 0; k < 4; k++)
        {
            i = Random.Range(0, 4);
            j = Random.Range(0, 4);
            n = Random.Range(0, 3);
            if (array[i, j] != 0)
            {
                i = Random.Range(0, 4);
                j = Random.Range(0, 4);
            }

            array[i, j] = num[n];
        }
    }

    #region 上下左右操作
    
    /// <summary>
    /// 向右移动
    /// </summary>
    public void _X_Right(int[,] array)
    {
        int[] _right=new int[4];
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                _right[j] = array[i,j];
                if (j==array.GetLength(1)-1)
                {
                   margeArray(_right);
                    for (int k = 0; k < _right.Length; k++)
                    {
                        array[i, k] = _right[k];
                    }
                }
            }
        }
    }

    public void _X_left(int[,] array)
    {
        Stack<int> _leftStack = new Stack<int>();
        int[] _left = new int[4];
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                _leftStack.Push(array[i,j]);
             
                if (j==array.GetLength(1)-1)
                {
                    _left = _leftStack.ToArray();
                    _leftStack.Clear();
                    margeArray(_left);
                    foreach (var a in _left)
                    {
                        _leftStack.Push(a);
                    }
                    for (int k = 0; k <_left.Length; k++)
                    {
                        array[i,k] = _leftStack.Pop();
                    }
                    _leftStack.Clear();
                }
            }
        }
    }

    public void _Y_Up(int[,] array)
    {
        Stack<int> _leftStack = new Stack<int>();
        int[] _left = new int[4];
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                _leftStack.Push(array[j,i]);
              
                if (j==array.GetLength(1)-1)
                {
                    _left = _leftStack.ToArray();
                    _leftStack.Clear();
                    margeArray(_left);
                    foreach (var a in _left)
                    {
                        _leftStack.Push(a);
                    }
                    for (int k = 0; k < _left.Length; k++)
                    {
                        array[k,i] = _leftStack.Pop();
                    }
                    _leftStack.Clear();
                }
            }
        }
    }

    public void _Y_Down(int[,] array)
    {
        int[] _right=new int[4];
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                _right[j] = array[j,i];
                if (j==array.GetLength(1)-1)
                {
                    margeArray(_right);
                    for (int k = 0; k < _right.Length; k++)
                    {
                        array[k, i] = _right[k];
                    }
                }
            }
        }
        
    }
    #endregion

    #region 合并移动
    
    /// <summary>
    /// 合并一维数组
    /// </summary>
    /// <param name="array"></param>
    private bool isEnd = false;
    public void margeArray(int[] array)
    {
        moveArray(array);
        bool isMargeOne = false;
        for (int i = array.Length - 1; i > 0; i--)
        {
            if (isMargeOne)
            {
                return;
            }
            if (i == array.Length - 1 && array[i] == array[i - 1] && array[i - 2] == array[i - 3])
            {
                array[i] += array[i];
                array[i - 1] = 0;
                array[i - 2] += array[i - 2];
                array[i - 3] = 0;
                moveArray(array);
                isMargeOne = true;
              
            }
            else if (array[i] == array[i - 1])
            {
                array[i] += array[i];
                array[i - 1] = 0;
                moveArray(array);
                isMargeOne = true;
            }

           
        }
        isEnd=!isHaveKong();
    }

    /// <summary>
    /// //移动完判断是否有空
    /// </summary>
    /// <returns></returns>
    public bool isHaveKong()
    {
        
        int num=0;
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                if (array[i,j]==0)
                {
                    num++;
                }
            }
        }
        if (num==0)
            return false;

        return true;
    }

    /// <summary>
    /// 移动一维数组
    /// </summary>
    /// <param name="array"></param>
    public void moveArray(int[] array)
    {
        
        int move = 0;
        for (int i = 0; i <array.Length-1 ; i++)
        {
            if (array[i]!=0&&array[i+1]==0)
            {
                array[i + 1] = array[i];
                array[i]=0;
                move++;
                // isMoveToRandom2 = true;
            }
        }
        if (move != 0)
            moveArray(array); 
        
    }

    #endregion

}


